package Session;

use strict;
use warnings;
use File::HomeDir;
use IMBK::Data::Categories;
use IMBK::Data::Keywords;

sub new {
	my $class = shift;
	my %args = @_;
	my $self = { Settings_Dir => default_settings_dir(), 
					Categories_Source_Name => 'CategoriesLocalDatabase',
					Categories_Database_Filename => 'categories.db', 
					Categories_Database_Driver => 'dbi:SQLite',
					Keywords_Search_Engine_Name = 'IQDB'
				};
	
	foreach my $key ( keys %args ) {
		$self->{$key} = $args{$key};
	}
	
	$self->{Settings_Dir} = check_path($self->{Settings_Dir});

	return bless $self, $class;
};

sub get_categories {
	my $self = shift;
	my $categories = undef;
	if ( not defined $self->{Categories} ) {
		$categories = Categories->new(%$self);
		$self->{Categories} = $categories;
	} else {
		$categories = $self->{Categories};
	}
	return $categories->get_categories(@_);
};

sub get_keywords {
	my $self = shift;
	my $keywords = undef;
	if ( not defined $self->{Keywords} ) {
		$keywords = Keywords->new(%$self);
		$self->{Keywords} = $keywords;
	} else [
		$keywords = $self->{Keywords};
	}
	return $keywords->get_keywords(@_);
};

sub clear_categories {
	my $self = shift;
	my $result = 1;
	my $file_path = $self->{Settings_Dir}.'/'.$self->{Categories_Database_Filename};
	$result = unlink($file_path) if ( -e $file_path );
	return $result;
}

sub default_settings_dir {
	my $_data_path = File::HomeDir->my_home;
	if ( not defined $_data_path ) {
		return undef;
	}

	$_data_path = $_data_path.'/'.'.imbk-downloader';
	return check_path($_data_path);
}

sub check_path {
	my $path = shift;
	$path =~ s/\\/\//g;
	if( not -e $path ) {
		mkdir($path) or die;
	}
	return $path;
}

1;